from datetime import datetime

from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse

from apps.aiauth.models import Users
from apps.career.models import Careerplan, CareerplanExperts
from apps.career.serializers import CareerSerializer, CareerDetailSerializer
from apps.message.models import Comments
from apps.message.serializers import CommentsSerializers
from apps.setup.models import Timeslot, Experts, Organizations
from apps.setup.serializers import TimesLotSerializer, ExpertsSerializers, OrganizationsSerializer
from utils import restful


# 获取专家
def ExpertList(request):
    experts = Experts.objects.all()
    data = ExpertsSerializers(experts, many=True).data
    return restful.ok(data=data)


# 获取时段
def TimesLot(request):
    timesLot = Timeslot.objects.all()
    data = TimesLotSerializer(timesLot, many=True).data
    return restful.ok(data=data)


# 获取班级
def Organization(request):
    cla = Organizations.objects.all()
    data = OrganizationsSerializer(cla, many=True).data
    return restful.ok(data=data)


# 保存职业规划，状态为0
def SaveCareerPlan(request):
    if request.POST:
        user_id = request.POST.get('user_id')
        user = Users.objects.get(user_id=user_id)
        title = request.POST.get('title')
        sub_message = request.POST.get('sub_message')
        create_time = datetime.now()
        is_studymaster = request.POST.get('is_studymaster')
        content = request.POST.get('content')
        content_html = request.POST.get('content_html')

        timeslot_id = request.POST.get('timeslot_id')
        if timeslot_id:
            timeslot = Timeslot.objects.get(timeslot_id=timeslot_id)
        else:
            timeslot = None
        careerplan = Careerplan.objects.create(
            title=title,
            sub_message=sub_message,
            timeslot_id=timeslot,
            is_studymaster=is_studymaster,
            create_time=create_time,
            is_dot='0',
            content=content,
            content_html=content_html,
            user_id=user,
            status='0'
        )
        experts_id_list = request.POST.getlist('experts_id_list')
        if experts_id_list:
            # 删除多余的专家
            obj = CareerplanExperts.objects.filter(
                ~Q(experts_id__in=experts_id_list) & Q(careerplan_id=careerplan.careerplan_id)
            )
            obj.delete()
            for experts_id in experts_id_list:
                expert = Experts.objects.get(experts_id=experts_id)
                careerplan_experts = CareerplanExperts.objects.create(
                    careerplan_id=careerplan,
                    create_time=create_time,
                    experts_id=expert
                )
        data = CareerSerializer(careerplan).data
        return restful.ok(data=data, message='保存成功！')

    return restful.method_error(message='请求出错！')


# 修改职业规划
def ModifyCareerPlan(request):
    if request.POST:
        careerplan_id = request.POST.get('careerplan_id')
        title = request.POST.get('title')
        sub_message = request.POST.get('sub_message')
        timeslot_id = request.POST.get('timeslot_id')
        if timeslot_id:
            timeslot = Timeslot.objects.get(timeslot_id=timeslot_id)
        else:
            timeslot = None
        update_time = datetime.now()
        is_studymaster = request.POST.get('is_studymaster')
        content = request.POST.get('content')
        content_html = request.POST.get('content_html')
        careerplan = Careerplan.objects.get(careerplan_id=careerplan_id)

        careerplan.title = title
        careerplan.sub_message = sub_message
        careerplan.timeslot_id = timeslot
        careerplan.is_studymaster = is_studymaster
        careerplan.update_time = update_time
        careerplan.content = content
        careerplan.content_html = content_html
        careerplan.save()

        experts_id_list = request.POST.getlist('experts_id_list')
        if experts_id_list:
            # 删除多余的专家
            obj = CareerplanExperts.objects.filter(
                ~Q(experts_id__in=experts_id_list) & Q(careerplan_id=careerplan.careerplan_id)
            )
            obj.delete()
            for experts_id in experts_id_list:
                expert = Experts.objects.get(experts_id=experts_id)
                try:
                    careerplan_experts = CareerplanExperts.objects.create(
                        careerplan_id=careerplan,
                        create_time=update_time,
                        experts_id=expert
                    )
                except:
                    pass

        data = CareerSerializer(careerplan).data
        return restful.ok(data=data, message='更新成功！')

    return restful.method_error(message='请求出错！')


# 提交职业规划，状态为1
def PublishCareerPlan(request):
    if request.POST:
        careerplan_id = request.POST.get('careerplan_id')
        user_id = request.POST.get('user_id')
        user = Users.objects.get(user_id=user_id)
        title = request.POST.get('title')
        sub_message = request.POST.get('sub_message')
        timeslot_id = request.POST.get('timeslot_id')
        timeslot = Timeslot.objects.get(timeslot_id=timeslot_id)
        create_time = datetime.now()
        publish_time = datetime.now()
        is_studymaster = request.POST.get('is_studymaster')
        content = request.POST.get('content')
        content_html = request.POST.get('content_html')
        # 如果有则修改
        if careerplan_id:
            careerplan = Careerplan.objects.get(careerplan_id=careerplan_id)
            careerplan.user_id = user
            careerplan.title = title
            careerplan.sub_message = sub_message
            careerplan.timeslot_id = timeslot
            careerplan.is_studymaster = is_studymaster
            careerplan.publish_time = publish_time
            careerplan.is_dot = '0'
            careerplan.status = 1
            careerplan.content = content
            careerplan.content_html = content_html
            careerplan.save()
        else:  # 没有则新建
            careerplan = Careerplan.objects.create(
                title=title,
                sub_message=sub_message,
                timeslot_id=timeslot,
                is_studymaster=is_studymaster,
                create_time=create_time,
                is_dot='0',
                content=content,
                content_html=content_html,
                user_id=user,
                status=1
            )
        experts_id_list = request.POST.getlist('experts_id_list')
        if experts_id_list:
            # 删除多余的专家
            obj = CareerplanExperts.objects.filter(
                ~Q(experts_id__in=experts_id_list) & Q(careerplan_id=careerplan.careerplan_id)
            )
            obj.delete()
            for experts_id in experts_id_list:
                expert = Experts.objects.get(experts_id=experts_id)
                try:
                    careerplan_experts = CareerplanExperts.objects.create(
                        careerplan_id=careerplan,
                        create_time=publish_time,
                        experts_id=expert
                    )
                except:
                    pass

        data = CareerSerializer(careerplan).data

        return restful.ok(message="提交成功！", data=data)

    return restful.method_error(message='请求出错！')


# 获取一条职业规划详细信息
def getCareerPlan(request):
    careerplan_id = request.GET.get('careerplan_id')
    careerplan = Careerplan.objects.get(careerplan_id=careerplan_id)
    data = CareerDetailSerializer(careerplan).data

    return restful.ok(data=data)


# 职业规划搜索
def CareerPlanList(request):
    pagenow = request.GET.get('pagenow', 1)
    size = request.GET.get('pagesize', 10)
    user_id = request.GET.get('user_id')
    status = request.GET.get('status')
    timeslot = request.GET.get('timeslot_id')
    organization_id = request.GET.get('organization_id')
    realName = request.GET.get('realName')
    student_id = request.GET.get('student_id')

    search_dict = {}

    if user_id:
        search_dict['user_id'] = user_id
    if status:
        search_dict['status'] = status
    if timeslot:
        search_dict['timeslot_id'] = timeslot
    if organization_id:
        search_dict['user_id__userinfo__organization_id'] = organization_id
    if realName:
        search_dict['user_id__realname__iexact'] = realName
    if student_id:
        search_dict['user_id__studentid'] = student_id
    plan = Careerplan.objects.filter(
        **search_dict,
    ).filter(status__in=[0, 1]).order_by('-create_time')

    page_obj = Paginator(plan, size)
    page_data = page_obj.get_page(pagenow)
    totalcount = page_obj.count
    serializer = CareerSerializer(page_data.object_list, many=True)

    data = serializer.data

    return JsonResponse({
        'message': '请求成功！',
        'code': 200,
        'data': {
            'data': data,
            'totalcount': totalcount
        }
    })


# 删除职业规划，将status改为2
def DeleteCareerPlan(request):
    careerplan_id = request.GET.get('careerplan_id')
    status = Careerplan.objects.get(careerplan_id=careerplan_id)
    status.status = '2'
    status.save()
    return restful.ok(message='删除成功！')


# 获取职业规划评论，type1是职业规划，0是简历
# status 1为正常，0为删除，2仅老师可见，默认1
def CareerComments(request):
    search_dict = {
        'type': '1',
        'status': '1'
    }
    user_id = request.GET.get('user_id')
    experts_id = request.GET.get('experts_id')
    pagenow = request.GET.get('pagenow', 1)
    if user_id:
        search_dict['user_id'] = user_id
    if experts_id:
        search_dict['experts_id'] = experts_id
    comments = Comments.objects.filter(
        **search_dict
    ).order_by('-create_time')
    page_obj = Paginator(comments, 10)
    page_data = page_obj.get_page(pagenow)
    totalcount = page_obj.count
    data = CommentsSerializers(page_data.object_list, many=True).data

    return JsonResponse({
        'message': '请求成功！',
        'code': 200,
        'data': {
            'data': data,
            'totalcount': totalcount
        }
    })
    # return restful.ok(data=data)


# 添加评论
def AddComments(request):
    careerplan_id = request.POST.get('careerplan_id')
    careerplan = Careerplan.objects.get(careerplan_id=careerplan_id)
    type = request.POST.get('type')
    user_id = request.POST.get('user_id')
    user = Users.objects.get(user_id=user_id)

    experts_id = request.POST.get('experts_id')
    expert = Experts.objects.get(experts_id=experts_id)
    content = request.POST.get('content')
    is_author = request.POST.get('is_author')
    status = request.POST.get('status')
    create_time = datetime.now()

    comment = Comments.objects.create(
        careerplan_id=careerplan,
        type=type,
        user_id=user,
        experts_id=expert,
        content=content,
        is_author=is_author,
        status=status,
        create_time=create_time
    )
    data = CommentsSerializers(comment).data
    return restful.ok(data=data, message='评论成功！')
